package org.jeecg.modules.demo.hdspecialsupervision.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.hdfocusareas.entity.HdFocusAreas;
import org.jeecg.modules.demo.hdfocusareas.service.IHdFocusAreasService;
import org.jeecg.modules.demo.hdspecialsupervision.entity.HdSpecialSupervision;
import org.jeecg.modules.demo.hdspecialsupervision.service.IHdSpecialSupervisionService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

 /**
 * @Description: 专项监督
 * @Author: jeecg-boot
 * @Date:   2025-07-01
 * @Version: V1.0
 */
@Tag(name = "专项监督")
@RestController
@RequestMapping("/hdspecialsupervision/hdSpecialSupervision")
@Slf4j
public class HdSpecialSupervisionController extends JeecgController<HdSpecialSupervision, IHdSpecialSupervisionService> {
	@Autowired
	private IHdSpecialSupervisionService hdSpecialSupervisionService;

	@Autowired
	private ISysDepartService sysDepartService;

	 @Autowired
	 private ISysBaseAPI sysBaseAPI;
	 @Autowired
	 private IHdFocusAreasService hdFocusAreasService;
	
	/**
	 * 分页列表查询
	 *
	 * @param hdSpecialSupervision
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "专项监督-分页列表查询")
	@Operation(summary = "专项监督-分页列表查询", description = "专项监督-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<HdSpecialSupervision>> queryPageList(HdSpecialSupervision hdSpecialSupervision,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
        // 自定义查询规则
        Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
        // 自定义多选的查询规则为：LIKE_WITH_OR
        customeRuleMap.put("focusAreas", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("departName", QueryRuleEnum.LIKE_WITH_OR);
        QueryWrapper<HdSpecialSupervision> queryWrapper = QueryGenerator.initQueryWrapper(hdSpecialSupervision, req.getParameterMap(),customeRuleMap);
		Page<HdSpecialSupervision> page = new Page<HdSpecialSupervision>(pageNo, pageSize);
		IPage<HdSpecialSupervision> pageList = hdSpecialSupervisionService.page(page, queryWrapper);
		return Result.OK(pageList);
	}


	 /**
	  * 分页列表查询
	  *
	  * @param hdSpecialSupervision
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 //@AutoLog(value = "专项监督-分页列表查询")
	 @Operation(summary = "专项监督-分页列表查询", description = "专项监督-分页列表查询")
	 @GetMapping(value = "/listByDepart")
	 public Result<IPage<HdSpecialSupervision>> listByDepart(HdSpecialSupervision hdSpecialSupervision,
															  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
															  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
															  HttpServletRequest req) {
		 //获取登录人的信息
		 LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 String pid = req.getParameter("pid");
		 if (loginUser.getRoleCode().equals("admin")||loginUser.getRoleCode().equals("leader")){
			 // 自定义查询规则
			 Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
			 // 自定义多选的查询规则为：LIKE_WITH_OR
			 customeRuleMap.put("focusAreas", QueryRuleEnum.LIKE_WITH_OR);
			 customeRuleMap.put("departName", QueryRuleEnum.LIKE_WITH_OR);
			 QueryWrapper<HdSpecialSupervision> queryWrapper = QueryGenerator.initQueryWrapper(hdSpecialSupervision, req.getParameterMap(),customeRuleMap);
			 queryWrapper.eq("pid",pid);
			 Page<HdSpecialSupervision> page = new Page<HdSpecialSupervision>(pageNo, pageSize);
			 IPage<HdSpecialSupervision> pageList = hdSpecialSupervisionService.page(page, queryWrapper);
			 return Result.OK(pageList);
		 }
		 else {
			 String id = loginUser.getDepartIds();
			 String departName = sysDepartService.getDepartNameById(id);
			 System.out.println("departName = " + departName);
			 // 自定义查询规则
			 Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
			 // 自定义多选的查询规则为：LIKE_WITH_OR
			 customeRuleMap.put("focusAreas", QueryRuleEnum.LIKE_WITH_OR);
			 QueryWrapper<HdSpecialSupervision> queryWrapper = QueryGenerator.initQueryWrapper(hdSpecialSupervision, req.getParameterMap(),customeRuleMap);
			 queryWrapper.eq("pid",pid)
					 .eq("company_department",departName);
			 Page<HdSpecialSupervision> page = new Page<HdSpecialSupervision>(pageNo, pageSize);
			 IPage<HdSpecialSupervision> pageList = hdSpecialSupervisionService.page(page, queryWrapper);
			 return Result.OK(pageList);
		 }

//		 return Result.OK(pageList);
	 }


	/**
	 *   添加
	 *
	 * @param hdSpecialSupervision
	 * @return
	 */
	@AutoLog(value = "专项监督-添加")
	@Operation(summary = "专项监督-添加", description = "专项监督-添加")
	@RequiresPermissions("hdspecialsupervision:hd_special_supervision:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody HdSpecialSupervision hdSpecialSupervision) {
		hdSpecialSupervisionService.save(hdSpecialSupervision);
		return Result.OK("添加成功！");
	}

	 /*
	  * 批量添加
	  *
	  * @param hdSpecialSupervisionList
	  * @return
	  */
	 @AutoLog(value = "专项监督-批量添加")
	 @Operation(summary = "专项监督-批量添加", description = "专项监督-批量添加")
	 @PostMapping(value = "/addBatch")
	 public Result<String> addBatch(@RequestBody List<HdSpecialSupervision> hdSpecialSupervisionList) {
		 hdSpecialSupervisionService.saveBatch(hdSpecialSupervisionList);
		 return Result.OK("批量添加成功！");
	 }



	/**
	 *  编辑
	 *
	 * @param hdSpecialSupervision
	 * @return
	 */
	@AutoLog(value = "专项监督-编辑")
	@Operation(summary = "专项监督-编辑", description = "专项监督-编辑")
	@RequiresPermissions("hdspecialsupervision:hd_special_supervision:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody HdSpecialSupervision hdSpecialSupervision) {
		hdSpecialSupervisionService.updateById(hdSpecialSupervision);
		return Result.OK("编辑成功!");
	}


	 /**
	  *  编辑
	  *
	  * @param hdSpecialSupervision
	  * @return
	  */
	 @AutoLog(value = "专项监督-编辑")
	 @Operation(summary = "专项监督-编辑", description = "专项监督-编辑")
	 @RequiresPermissions("hdspecialsupervision:hd_special_supervision:update")
	 @RequestMapping(value = "/update", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> update(@RequestBody HdSpecialSupervision hdSpecialSupervision) {
		 hdSpecialSupervisionService.updateById(hdSpecialSupervision);
		 return Result.OK("编辑成功!");
	 }

	 /**
	  *  编辑
	  *
	  * @param hdSpecialSupervision
	  * @return
	  */
	 @AutoLog(value = "专项监督-重新上传")
	 @Operation(summary = "专项监督-重新上传", description = "专项监督-重新上传")
	 @RequiresPermissions("hdspecialsupervision:hd_special_supervision:reUpload")
	 @RequestMapping(value = "/reUpload", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> reUpload(@RequestBody HdSpecialSupervision hdSpecialSupervision) {
		 hdSpecialSupervisionService.updateById(hdSpecialSupervision);
		 return Result.OK("重新上传!");
	 }



	 /**
	  *  编辑
	  *
	  * @param hdSpecialSupervision
	  * @return
	  */
	 @AutoLog(value = "专项监督-审核")
	 @Operation(summary = "专项监督-审核", description = "专项监督-审核")
	 @RequiresPermissions("hdspecialsupervision:hd_special_supervision:audit")
	 @RequestMapping(value = "/audit", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> audit(@RequestBody HdSpecialSupervision hdSpecialSupervision) {
		 if (hdSpecialSupervision.getFlag().equals("2")){
			 String userName = sysBaseAPI.getUserByName(hdSpecialSupervision.getUpdateBy()).getUsername();
			 MessageDTO message = new MessageDTO("系统", userName,
					 "信息填写错误，请修改",
					 hdSpecialSupervision.getOpinion());
			 sysBaseAPI.sendSysAnnouncement(message);
			 hdSpecialSupervisionService.updateById(hdSpecialSupervision);
		 }else{
			 hdSpecialSupervisionService.updateById(hdSpecialSupervision);
		 }
		 return Result.OK("编辑成功!");
	 }

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "专项监督-通过id删除")
	@Operation(summary = "专项监督-通过id删除", description = "专项监督-通过id删除")
	@RequiresPermissions("hdspecialsupervision:hd_special_supervision:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		hdSpecialSupervisionService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "专项监督-批量删除")
	@Operation(summary = "专项监督-批量删除", description = "专项监督-批量删除")
	@RequiresPermissions("hdspecialsupervision:hd_special_supervision:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.hdSpecialSupervisionService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "专项监督-通过id查询")
	@Operation(summary = "专项监督-通过id查询", description = "专项监督-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<HdSpecialSupervision> queryById(@RequestParam(name="id",required=true) String id) {
		HdSpecialSupervision hdSpecialSupervision = hdSpecialSupervisionService.getById(id);
		if(hdSpecialSupervision==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(hdSpecialSupervision);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param hdSpecialSupervision
    */
    @RequiresPermissions("hdspecialsupervision:hd_special_supervision:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HdSpecialSupervision hdSpecialSupervision) {
        return super.exportXls(request, hdSpecialSupervision, HdSpecialSupervision.class, "专项监督");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("hdspecialsupervision:hd_special_supervision:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HdSpecialSupervision.class);
    }

	 @Operation(summary = "专项监督-导出excel合并单元格", description = "专项监督-导出excel合并单元格")
	 @GetMapping(value = "/exportXlsMergeCells")
	 public Result<byte[]> exportXlsMergeCells(HttpServletRequest request,HdSpecialSupervision hdSpecialSupervision) throws IOException {
		 // Step.1 组装查询条件
		 QueryWrapper<HdSpecialSupervision> queryWrapper =new QueryWrapper<>(hdSpecialSupervision);
		 // 过滤选中数据
		 String selections = request.getParameter("selections");
//		 System.out.println("selections = " + selections);
//		 String department = request.getParameter("department");
		 String focusAreas = request.getParameter("focusAreas");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 System.out.println("selectionList = " + selectionList);
			 queryWrapper.in("id",selectionList);
		 }  else if (oConvertUtils.isNotEmpty(focusAreas)) {
			 queryWrapper.eq("focus_areas",focusAreas);
		 }
		 // Step.2 获取导出数据
		 List<HdSpecialSupervision> exportList = hdSpecialSupervisionService.list(queryWrapper);
		 // 2. 生成Excel字节数组
		 byte[] excelBytes = hdSpecialSupervisionService.generateExcelBytes(exportList);
		 return Result.OK(excelBytes);
	 }

	 @Operation(summary="专项监督-查询所有部门的填报率", description="专项监督-查询所有部门的填报率")
	 @GetMapping(value = "/queryAllDepartmentFillRate")
	 public Result<Map<String, Object>> queryAllDepartmentFillRate(HdSpecialSupervision hdSpecialSupervision) {
		 Map<String, Object> result = new HashMap<>();
		 Long total = 0L;
		 Long complete=0L;
		 double fillRate=0.0;
		 List<SysDepart> departList = sysDepartService.list();
		 for (int i = 0; i < departList.size(); i++) {
			 total=hdSpecialSupervisionService.count(new QueryWrapper<HdSpecialSupervision>().eq("company_department", departList.get(i).getDepartName()));
			 complete=hdSpecialSupervisionService.count(new QueryWrapper<HdSpecialSupervision>().eq("company_department", departList.get(i).getDepartName()).in("flag", "1", "2","3"));
			 if (total!=0L){
				 fillRate=(double)complete/total;
				 //fillRate保留小数点后两位
				 fillRate=new BigDecimal(fillRate).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
				 result.put(departList.get(i).getDepartName(), fillRate);
			 }
		 }
		 return Result.OK(result);

	 }


	 /**
	  * 统计重点领域数量
	  *
	  * @return
	  */
	 @AutoLog(value = "统计重点领域数量")
	 @Operation(summary = "统计重点领域数量", description = "统计重点领域数量")
	 @GetMapping(value = "/selectResult")
	 public Result<Map<String, Object>>selectResult() {
		Map<String, Object> resultMap = new HashMap<>();

		 // 获取所有重点领域
		 List<HdFocusAreas> hdFocusAreasList = hdFocusAreasService.list();

		 if (hdFocusAreasList != null && !hdFocusAreasList.isEmpty()) {
			 for (HdFocusAreas focusArea : hdFocusAreasList) {
				 // 获取重点领域名称
				 String areaName = focusArea.getFocusAreas(); // 假设实体中有getName()方法

				 // 统计该重点领域对应的数量
				 // 这里假设HdSpecialSupervisionService有按重点领域查询数量的方法
				 int count = hdSpecialSupervisionService.countByFocusAreaName(areaName);
				 resultMap.put(areaName, count);
			 }
		 }
	return Result.OK(resultMap);
	 }


 }
